import pymysql, datetime
from .logger import get_logger

class Recorder:
    def __init__(self, cfg):
        self.log = get_logger("Recorder")
        self.conn = pymysql.connect(**cfg["db"], autocommit=True)
        self.table = cfg["table"]
        self._create_table()

    def _create_table(self):
        with self.conn.cursor() as cur:
            cur.execute(f"""
                CREATE TABLE IF NOT EXISTS {self.table}(
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    ts DATETIME,
                    location VARCHAR(64),
                    trigger_type VARCHAR(32),
                    img_path VARCHAR(256)
                )
            """)

    def write(self, trigger_type, img_path):
        sql = f"INSERT INTO {self.table}(ts,location,trigger_type,img_path) VALUES (%s,%s,%s,%s)"
        with self.conn.cursor() as cur:
            cur.execute(sql, (datetime.datetime.now(), "front_gate", trigger_type, img_path))
        self.log.info("写入数据库：type=%s, img=%s", trigger_type, img_path)